package com.tianji.aigc.advisor;

import cn.hutool.core.convert.Convert;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.memory.MyChatMemoryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatResponse;

public class RecordOptimizationAdvisor implements BaseAdvisor {

    private static final Logger log = LoggerFactory.getLogger(RecordOptimizationAdvisor.class);
    private final MyChatMemoryRepository memoryRepository;

    public RecordOptimizationAdvisor(MyChatMemoryRepository memoryRepository) {
        this.memoryRepository = memoryRepository;
    }

    @Override
    public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
        return chatClientRequest;
    }

    @Override
    public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
        ChatResponse response = chatClientResponse.chatResponse();
        assert response != null;
        String text = response.getResult().getOutput().getText();
        log.info("查看智能体响应结果：{}", text);
        AgentTypeEnum agentTypeEnum = AgentTypeEnum.agentNameOf(text);
        if (agentTypeEnum != null) {
            String key = ChatMemory.CONVERSATION_ID;
            String conversationId = Convert.toStr(chatClientResponse.context().get(key));
            memoryRepository.optimization(conversationId);
        }

        return chatClientResponse;
    }

    @Override
    public int getOrder() {
        return Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER - 100;
    }
}
